/*
 * Simple database connection layer. Ask for a connection and you will get one
 */
package com.spartancoder.accommodation.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * Simple database abstraction layer
 *
 * @author andrei
 */
public class Database {

	private static Logger log = Logger.getLogger(Database.class.getName());
	private static Map<String, Database> instances = new HashMap<String, Database>();
	private static boolean driverLoaded = false;

	public static Database getInstance() {
		return getInstance("accommodation");
	}

	public static Database getInstance(String db) {

		if (!driverLoaded) {
			log.info("Loading mysql jdbc driver");
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
			} catch (Exception ex) {
				log.severe(ex.toString());
				throw new Error(ex);
			}
			driverLoaded = true;
		}

		if (!instances.containsKey(db)) {
			try {
				log.info("Loading database configuration");
				Properties conf = new Properties();
				String configFile = "/com/spartancoder/accommodation/db/" + db + ".properties";
				conf.load(Database.class.getResourceAsStream(configFile));
				instances.put(db, new Database(conf));
			} catch (IOException ex) {
				log.severe(ex.toString());
				throw new Error(ex);
			}
		}

		return instances.get(db);
	}
	
	private String url, user, password;

	private Database(Properties conf) {
		url = conf.getProperty("db.url");
		user = conf.getProperty("db.user");
		password = conf.getProperty("db.password","");
	}

	public Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, user, password);
	}
}
